﻿using Admin.Core.Common.Attributes;
using Admin.Core.Common.Auth;
using Admin.Core.Common.Configs;
using Admin.Core.Common.Input;
using Admin.Core.Common.Output;
using Admin.Core.Common.ParamInput;
using Admin.Core.Model.Xsproject;
using Admin.Core.Repository.Xsproject.Project;
using Admin.Core.Repository.Xsproject.TaskHis;
using Admin.Core.Repository.Xsproject.TaskItem;
using Admin.Core.Service.Xsproject.TaskHis.Input;
using Admin.Core.Service.Xsproject.TaskHis.Output;
using AutoMapper;
using Microsoft.Extensions.Options;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Admin.Core.Service.Xsproject.TaskHis
{
    public class TaskHisService: ITaskHisService
    {
        private readonly IUser _user;
        private readonly IMapper _mapper;
        private readonly ITaskHisRepository _taskHisRepository;
        private readonly ITaskItemRepository _taskItemRepository;
        private readonly IProjectRepository _projectRepository;
        private readonly UploadConfig _uploadConfig;
        public TaskHisService(IUser user, IMapper mapper
            , ITaskHisRepository taskHisRepository
            , IOptionsMonitor<UploadConfig> uploadConfig
            , ITaskItemRepository taskItemRepository
            , IProjectRepository projectRepository
            )
        {
            _user = user;
            _mapper = mapper;
            _uploadConfig = uploadConfig.CurrentValue;
            _taskHisRepository = taskHisRepository;
            _taskItemRepository = taskItemRepository;
            _projectRepository = projectRepository;
        }



        /// <summary>
        /// 更新任务
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [Transaction]
        public async Task<IResponseOutput> AddAsync(TaskHisAddInput input)
        {
            var entity = _mapper.Map<TaskHisEntity>(input);
            entity.TenantId = _user.TenantId;
            entity.ActorId = _user.Id;
            if (!string.IsNullOrEmpty(entity.FileName))
            {
                entity.FileName = entity.FileName.Substring(0, entity.FileName.LastIndexOf("."));
            }
            var rs = await _taskItemRepository.GetAsync<TaskItemEntity>(input.TaskId);
            if (input.TaskFlag == 1) 
            {
                //任务未结束
                var id = (await _taskHisRepository.baseRepository.InsertAsync(entity)).Id;
                rs.Progress = input.Progress;
                rs.ActualEndDate = input.ActualEndDate;
                var r = await _taskItemRepository.baseRepository.UpdateAsync(rs);
                return ResponseOutput.Ok(r > 0);
            }
            else 
            {
                entity.Progress = 100;
                var id = (await _taskHisRepository.baseRepository.InsertAsync(entity)).Id;
                //任务结束
                rs.Progress = 100;
                rs.TaskFlag = 2;
                rs.ActualEndDate = input.ActualEndDate;
                var r = await _taskItemRepository.baseRepository.UpdateAsync(rs);
                var count = await _taskItemRepository.baseRepository.Select.Where(x => x.ParentId == rs.ParentId && x.Id != rs.Id && x.TaskFlag != 2).CountAsync();
                if (count == 0)
                {
                    //最后一个完成任务
                    var parent = await _taskItemRepository.GetAsync<TaskItemEntity>(rs.ParentId.Value);
                    //阶段的状态改成完成
                    parent.Status = 2;
                    var r1 = await _taskItemRepository.baseRepository.UpdateAsync(parent);
                    //判断该阶段是否具有同顺位的阶段
                   var count1 = await _taskItemRepository.baseRepository.Select.Where(x => x.FlowId == parent.FlowId && x.ParentId == 0 && x.ProjectId == parent.ProjectId && x.Status!=2).CountAsync();
                    if (count1 == 0)
                    {
                        //下一个阶段开启  获取下一阶段
                        var nextx = await _taskItemRepository.baseRepository.Select.Where(x => x.ProjectId == rs.ProjectId && x.ParentId == 0 && x.FlowId > parent.FlowId).Count(out var total1).ToListAsync();
                        if (total1 > 0)
                        {
                            var maxentities = nextx.Where(x => x.FlowId == nextx.Min(z => z.FlowId)).ToList();
                            //阶段状态改未待处理
                            maxentities.ForEach(x =>
                            {
                                x.Status = 0;
                            });
                            await _taskItemRepository.baseRepository.UpdateAsync(maxentities);
                        }
                        else
                        {
                            //项目完成
                            var result  = await _projectRepository.baseRepository.Select.Where(x => x.Id == parent.ProjectId && x.Status == 1).Count(out var total).ToOneAsync();
                            if (total == 0)
                            {
                                return ResponseOutput.NotOk("项目不存在，或者状态出现异常，请联系IT处理!");
                            }else
                            {
                                result.Status = 2;
                                await _projectRepository.baseRepository.UpdateAsync(result);
                            }
                        }
                    }

                }
                return ResponseOutput.Ok(r > 0);
            }
           
        }
        public async Task<IResponseOutput> PageAsync(PageInput<ConmonFilterIdInput> input)
        {
            var config = _uploadConfig.Calfile;
            var key = input.Filter?.Id;
            var list = await _taskHisRepository.baseRepository.Select
            .Where(x => x.TaskId.Equals(key))
            .Count(out var total)
            .OrderByDescending(true, c => c.Id)
            //.Page(input.CurrentPage, input.PageSize)
            .ToListAsync(a => new TaskHisListOutput
            {
                FilePath = string.IsNullOrEmpty(a.FilePath)?"": config.RequestPath + "/"+ a.FilePath,
                ActorName = a.Actor.NickName,
            });
            //var data = new PageOutput<TaskHisListOutput>()
            //{
            //    List = list,
            //    Total = total
            //};
            var data = new VxePageOutPut<TaskHisListOutput>()
            {
                Result = list,
                Page = new VxePage { currentPage = input.CurrentPage, pageSize = input.PageSize, total = total, totalResult = total }
            };
            return ResponseOutput.Ok(data);
        }

    }
}
